// miniprogram/pages/Tournament/match.js
import{
viewed,
} from '../../http/game'
const app = getApp();
const newspagecount = 5;
const thurmbpagecount = 10;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    staticUrl: app.globalData.staticUrl,
    matchid: "",
    matchinfo: "",
    baseimgaeUrl: app.globalData.imageBaseUrl,
    currentTab: 0,
    matchleaders: [],
    news_items: [],
    drawsheet: [],
    matchfiledlist: [],
    thurmbs: [],
    newspageoffset: 0,
    thurmbspageoffset: 0,
    isloadingthurmbs: false,
    isloadingnews: false,
    currentTabmatchinfo: 0,
    matchdetail: undefined,
    islogin: false,
    top: 999,
    timer: '',
    mytour:'',
    error: '',
    playerinfo: {},
    distributorList: [],
    hasDistributor: false,
    iscommitregister: false,
    PlayerHotelinfo: "",
    eventlistsinfo: "",
    register_info: {
      "mt_id": "",
      "userID": "",
      "userOpenid": "",
      "PlayerPoles": "",
      "GroupID": "",
      "PlayerSize": "", //  尺码 
      "PlayerIsHotel": "", //是否入住官方酒店
      "PlayerIsCaddie": "", // 是否带球童
      "PlayerHotelStart": "", // 入住日期
      "PlayerHotelEnd": "", // 离开日期
      "PlayerHotelRoom": "", //  单人间/双人间
      "events_id": "",
    },
    isvistor: true,
    PlayerSize: ["XS", "S", "L", "XL", "XXL", "XXS", "XXXL"],
    PlayerIsHotel: [{
      "value": 0,
      "name": "不入住",
      "ischecked": false
    }, {
      "value": 1,
      "name": "入住",
      "ischecked": false
    }],
    PlayerIsCaddie: [{
      "value": 0,
      "name": "不自带",
      "ischecked": false
    }, {
      "value": 1,
      "name": "自带",
      "ischecked": false
    }],
    PlayerHotelRoom: [{
        "value": 0,
        "name": "标准大床房",
        "ischecked": false
      },
      {
        "value": 1,
        "name": "标准双床房",
        "ischecked": false
      }
    ],
    groupshouldbe: "",

    error: "",
    isoverage: false,
    ischecknone: true,
    currentuserInfo: '',
    type:'',
    awards_img:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var matchid = options.matchid;
    var currenttab = options.currenttab;
    console.log(matchid, '----------matchid------');
    

    var scence = decodeURIComponent(options.scene);
    if(scence){
      var arrs = scence.split('&');
      if(arrs.length>1){
      matchid = arrs[0].split('=')[1];
     
      this.setData({
        matchid: matchid
      });
    }
     

      if(arrs.length>1){

       
          var type = arrs[1].split('=')[1];
          if(type == 's'){  //签到 
            this.setData({type:type});
            this.getpagedate(false);
              this.getsign();
              //return ;
             
              return;
          }
      }
    }

    //从分享过来的
    if (matchid) {

      this.setData({
        matchid: matchid
      });
      this.getpagedate(false);
      this.viewed();
    } else {
      var jsonmatchinfoobj = app.globalData.selectmatchinfo;
      console.log(jsonmatchinfoobj);
      if (!jsonmatchinfoobj) {
        wx.switchTab({
          url: '../index/index',
        })
        return;
      }

      if(currenttab){
        this.setData({
          currentTab: currenttab,

        });
      }
      else{
      if (jsonmatchinfoobj.matchstatuscode == 'R') {
        this.setData({
          currentTab: 7,

        });




      }
      if (jsonmatchinfoobj.matchstatuscode == 'C') {
        this.setData({
          currentTab: 2,

        });
      }
    }

      console.log(this.data.currentTab);

      this.setData({
        matchinfo: jsonmatchinfoobj,


      });
      wx.setNavigationBarTitle({
        title: jsonmatchinfoobj.matchname
      })



      this.getpagedate(false);
      
      this.viewed();
      if (jsonmatchinfoobj.matchstatuscode == 'O') { //正在进行中 后台实时刷新比赛成绩数据
        this.setData({
          currentTab: 2
        });
        var that = this;
        if (that.data.timer != '') {
          clearInterval(that.data.timer);
        }
        that.data.timer = setInterval(function () {
          that.getpagedate(true);
          console.log(app.globalData.refreshtime / 1000 + "秒了----------------------------------------------------")
        }, app.globalData.refreshtime)
      }
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    console.log("onShow");
    this.setData({
      currentuserInfo: app.globalData.userInfo
    });

    if (this.data.currentTab == 7) {
      console.log("islogin");
      if (app.checkislogin()) {
        console.log("islogin");
        this.getregisterinfo();
      } else {
        wx.showToast({
          title: '请先登陆',
          icon: "none"
        })
        wx.navigateTo({
          url: '../login/login',
        })
        return;

      }
    }
    if(this.data.type){
       this.getsign();
       // this.getpagedate(false);
       // this.viewed();
       
       //this.viewed();
    }
   


  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    var that = this;
    if (that.data.timer != '') {
      clearInterval(that.data.timer);
    }
    this.viewed(true);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 显示标题栏进度条效果
    wx.showNavigationBarLoading();
    if (this.data.currentTab == 6) {
        this.setData({thurmbspageoffset:1});
      
    } else if (this.data.currentTab == 5) {
      this.setData({newspageoffset:1});
      
    }
    this.getpagedate(true);

    // 取消标题栏进度条效果
    wx.hideNavigationBarLoading();
    // 取消页面刷新动画
    wx.stopPullDownRefresh();


  },
  onResize: function (res) {
    this.onShow();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.currentTab == 6) {
      if (!this.data.isloadingthurmbs) {
        console.log(this.data.isloadingthurmbs);
        this.getthurmbs(this.data.thurmbpagecount, this.data.thurmbspageoffset);
      }
    } else if (this.data.currentTab == 5) {
      if (!this.data.isloadingnews) {
        this.getArtLists(this.data.newspagecount, this.data.newspageoffset);
      }
    }
  },

  /**
   * 用户分享朋友圈
   */
  /*
  onShareTimeline() {
    var that = this;
    var query = 'matchid=' + that.data.matchinfo.matchid;


    return {
      title: that.data.matchinfo.matchname + '--赛事页面-- ' + app.langpagcke.apptitle[0] + " " + app.langpagcke.apptitle[1] + '官方小程序', // 默认是小程序的名称(可以写slogan等)
      imageUrl: that.data.matchinfo.matchlogo? that.data.matchinfo.matchlogo:'/images/iconlogo.png',
      query: query,

    }

  },*/



  /**
   * 用户点击右上角分享
   */
  /*
  onShareAppMessage: function (options) {
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title: that.data.matchinfo.matchname + '--赛事页面-- ' + app.langpagcke.apptitle[0] + " " + app.langpagcke.apptitle[1] + '官方小程序', // 默认是小程序的名称(可以写slogan等)
      path: '/pages/Tournament/match?matchid=' + that.data.matchinfo.matchid, // 默认是当前页面，必须是以‘/’开头的完整路径
      imageUrl: that.data.matchinfo.matchlogo? that.data.matchinfo.matchlogo:'/images/logo.png',
      //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log(shareObj);
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调（转发成不成功都会执行）
      }

    };
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      var eData = options.target.dataset;
      console.log(eData.id); // shareBtn
      // 此处可以修改 shareObj 中的内容

    }
    // 返回shareObj
    console.log(shareObj);
    return shareObj;
  },*/


  ///页面滚动事件
  onPageScroll: function (e) {
    var resultobj;
    var idobj = "#";
    if (this.data.currentTab == 1) {
      idobj += "result"

    } else if (this.data.currentTab == 2) {

      idobj += "slefscoring"
    } else if (this.data.currentTab == 3) {
      idobj += "drawsheet"
    } else {
      return;
    }

    resultobj = this.selectComponent(idobj);
    console.log(resultobj);
    var that = this;
    wx.createSelectorQuery().select(idobj).boundingClientRect(function (rect) {
      that.setData({
        top: rect.top // 节点的高度
      })
      resultobj._scrollTopFun(e);
    }).exec();

  },


  getsign:function(){
    var that = this;
    if (app.checkislogin()) {
      console.log("islogin");
        app.user_sign(this.data.matchid,function(res){
          if (res.data.errorcode.code == "ok") {
                that.setData({type:''});
                if(res.data.errorcode.message == '0'){//已经签过到了
                  wx.showToast({
                    title: '已经签过到了',
                  })
                  that.getpagedate(false);
                  that.viewed();
                }
                else{
                //跳转到成功页面
                var succuss = {
                  message: res.data.data.UserTrueName + "\n" + res.data.data.matchname + "\n 现场签到成功",
                  time: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
                  back: true,
                  buttoninfo: "返回"
                }
                // wx.hideLoading();
    
                wx.navigateTo({
                  url: '/pages/succuss/index?succuss=' + JSON.stringify(succuss)
                })

               
              }
              // that.wxpay(register_id);
            }
        },function(){return;})
    } else {
      wx.showToast({
        title: '请先登陆',
        icon: "none"
      })
      wx.navigateTo({
        url: '../login/login',
      })
      return;

    }
  },

  
  viewed:function(ishide) {
    var  userInfo = app.globalData.userInfo;
    //console.log(user_id);
    let{matchid,matchinfo} = this.data;
    var user_id = userInfo.userID;
    //var player_id = userInfo.player_id || '';
    matchid = (matchid)?matchid:matchinfo.matchid;
    console.log(matchid);
    let{v_id} = this.data;
    if(ishide){
        if(v_id){
            
        }
        else{
            return;
        }
    }
    else{
        v_id = "";
    }

    var that = this;
    viewed({mt_id:matchid,user_id,v_id}).then(res => {
        console.log(res);
        if(res.errorcode.code='ok'){
        that.setData({
          v_id:res.data||"",
        })
        console.log(that.data.v_id);
      }
    })


    this.getDistributorList(matchid);


},



  getpagedate(autorefresh, matchinfo) {

    this.getmatchleaders(this.data.matchinfo, autorefresh);




  },



  //获取正在开始比赛的成绩
  getmatchleaders(matchinfo, autorefresh) {
    var that = this;
    console.log(matchinfo);
    if (!autorefresh) {
      wx.showNavigationBarLoading({
        success: (res) => {},
      })
    }
    app.getmatchleadersbyround((matchinfo) ? matchinfo.matchid : that.data.matchid, (matchinfo) ? that.data.matchinfo.currentround : 1, function (res) {
      var matchleaders = res.data.data.matchleaders;
      console.log("matchleaders");
      console.log(matchleaders);
      that.setData({
        matchleaders: matchleaders,
        matchinfo: res.data.data.matchinfo
      });
      if (!autorefresh) {
        if (that.data.matchinfo.matchstatuscode == 'R') {
          that.setData({
            currentTab: 7
          });
          that.onShow();
        } else if (that.data.matchinfo.matchstatuscode == 'O') {
          that.setData({
            currentTab: 2
          });
         
          if (that.data.timer != '') {
            clearInterval(that.data.timer);
          }
          that.data.timer = setInterval(function () {
            that.getpagedate(true);
            console.log(app.globalData.refreshtime / 1000 + "秒了----------------------------------------------------")
          }, app.globalData.refreshtime)
        
        } else if (that.data.matchinfo.matchstatuscode == 'C') {
          that.setData({
            currentTab: 2
          });
        }
      }
       //获取我的赛事
      that.getmytour();
      that.getroundholeststaics();
      that.getscoreststaics();
      that.gettstaics();
      if (!autorefresh) {
        that.getmatchdetail(false);
        that.getdrawsheet(false);
        that.getfiledlist(false);
        that.getArtLists(newspagecount, that.data.newspageoffset);
        that.getthurmbs(newspagecount, that.data.thurmbspageoffset);
        that.getmatchawards();
      }
      // app.globalData.currentMatch = that.data.match;    
    }, function () {
 
      wx.hideNavigationBarLoading({
        success: (res) => {},
      })
    });


  },


  getscoreststaics:function(){
    wx.showNavigationBarLoading();
    var that = this;
    app.getscoreststaics(this.data.matchid?this.data.matchid:this.data.matchinfo.matchid,function(res){
        console.log('getscoreststaics',res);
        if(res.data.data){
           that.setData({scoresstatisc:res.data.data});
           console.log(that.data.scoresstatisc);
        }
    },function(res){
      wx.hideNavigationBarLoading();
    })
  },

  gettstaics:function(){
    wx.showNavigationBarLoading();
    var that = this;
    app.getststaics(this.data.matchid?this.data.matchid:this.data.matchinfo.matchid,function(res){
        console.log('getsstatisc',res);
        if(res.data.data){
           that.setData({sstatisc:res.data.data});
           console.log(that.data.sstatisc);
        }
    },function(res){
      wx.hideNavigationBarLoading();
    })
  },

  getroundholeststaics:function(roundid){
      wx.showNavigationBarLoading();
      var that = this;
      app.getroundholeststaics(this.data.matchid?this.data.matchid:this.data.matchinfo.matchid,(roundid)?roundid:this.data.matchinfo.currentround,function(res){
          console.log(res);
          if(res.data.data){
             that.setData({holestatisc:res.data.data});
             console.log(that.data.holestatisc);
          }
      },function(res){
        wx.hideNavigationBarLoading();
      })
  },

  getholestatiscs:function(e){
      var roundid = e.detail;
      console.log("getholestatiscs");
      console.log(e);
      this.getroundholeststaics(roundid);
  },


  
 //获取我的比赛
 getmytour:function(){
  var userInfo =  app.globalData.userInfo?app.globalData.userInfo: wx.getStorageSync('userInfo');
  var that = this;
  if(!app.globalData.userInfo){
    app.globalData.userInfo = userInfo;
   }
  if(userInfo.player_id){
    app.getmytour(this.data.matchid?this.data.matchid:this.data.matchinfo.matchid,
      function(res){
        console.log("getmytour",res);
          if(res.data.data){
            that.setData({
              mytour:res.data.data
             })
           
            }
      },function(){
        wx.hideNavigationBarLoading({
          success: (res) => {},
        })
      })
  }
},

getDistributorList: function(match_id) {
  const that = this;
  wx.request({
    url: 'https://mapp.scoringchina.com/interface/xijiuopen/distributor/lists',
    data: {
      match_id: that.data.matchinfo.matchid
    },
    success: function(res) {
      if (res.data.errorcode.code === 'ok' && res.data.data.length > 0) {
        that.setData({
          distributorList: res.data.data,
          hasDistributor: true
        });
      }
    }
  });
},

  getmatchawards(){
    var that = this;
    wx.showNavigationBarLoading();
    app.getmatchawards(that.data.matchinfo.matchid,function (res) {
      console.log("getmatchawards-pic-res---------------------------------------------------------------------------------");
      console.log(res.data.data);
      
      if (res.data.data) {
        that.setData({
          // awards: res.data.data.awards,
          awards_img: res.data.data
        })
        }
        else{
          that.setData({
            // awards:[],
            awards_img:''
          })
        }
     
    }, function () {
        wx.hideNavigationBarLoading({
          success: (res) => {},
        })
    })
  },

  /////获取相册
  getthurmbs(count, offset) {

    var that = this;
    that.setData({
      isloadingthurmbs: true
    });
    wx.showNavigationBarLoading();
    app.getmedia("", that.data.matchinfo.matchid, "pic", function (res) {
      console.log("getmedia-pic-res",res);
      
      if (!res.data.data.news || res.data.data.news.length <= 0) {
        if(that.data.thurmbspageoffset>1){
        wx.showToast({
          title: '到底了',
          icon: 'none'
        })
      }
        return;
      }
      if (that.data.thurmbs && that.data.thurmbs.length > 0) {

        console.log(res.data);
        var newdata = res.data.data.news;
        var thurmbdata = that.data.thurmbs;
        console.log('before concat');
        console.log(thurmbdata);
        console.log(newdata);
        thurmbdata = thurmbdata.concat(newdata);

        console.log('after concat');
        console.log(thurmbdata);
        that.setData({
          thurmbs: thurmbdata
        });
        console.log('concat');
        console.log(that.data.thurmbs);
        //that.selectComponent('.thurmbslists').refreshImage(that.data.thurmbs);
      } else {
        that.setData({
          thurmbs: res.data.data.news
        })
        console.log('first');
        console.log(that.data.thurmbs);
      }
      that.setData({
        thurmbspageoffset: that.data.thurmbspageoffset + 1,
        isloadingthurmbs: false
      })
    }, offset?offset:that.data.thurmbspageoffset, count, function () {
        wx.hideNavigationBarLoading({
          success: (res) => {},
        })
    })

  },

  ///获取参赛球员
  getfiledlist(autorefresh) {
    var that = this;
    var matchid = that.data.matchinfo.matchid;
    if (!autorefresh) {
      wx.showNavigationBarLoading();
    }
    app.getplayers("", matchid, "0", "all", function (res) {
      console.log('filedelist-res');
      console.log(res);
      that.setData({
        matchfiledlist: res.data.data.players
      })
    }, function () {
      if (!autorefresh) {
        wx.hideNavigationBarLoading();
      }
    });


  },

  ///获取赛事相关规定
  getmatchdetail(autorefresh) {
    var that = this;
    var matchid = that.data.matchinfo.matchid;


    app.getmatchreglartion(matchid, function (res) {
      console.log(res);
      that.setData({
        matchregular: res.data.data.data
      });
      console.log(that.data.matchregular);
    })


    app.getmatchmatchschedule(matchid, function (res) {
      console.log(res);
      that.setData({
        schedul: res.data.data.data
      });
      console.log(that.data.schedul);
    })


    app.getmatchmatchhotel(matchid, function (res) {
      console.log(res);
      that.setData({
        hotel: res.data.data.data
      });
      console.log(that.data.hotel);
    })


    app.getmatchmatchshuttelbus(matchid, function (res) {
      console.log(res);
      that.setData({
        bus: res.data.data.data
      });
      console.log(that.data.bus);
    })




  },

  changerounddrawsheet: function (e) {
    var roundid = e.detail.roundno;
    console.log("changerounddrawsheet");
    console.log(e);
    this.getdrawsheet(false, roundid);
  },
  ///获取分组表
  getdrawsheet(autorefresh, roundid) {
    var that = this;
    var matchid = that.data.matchinfo.matchid;
    var roundno = (roundid) ? roundid : that.data.matchinfo.currentround;
    console.log(roundno);
    console.log(that.data.matchinfo);
    if (!autorefresh) {
      wx.showNavigationBarLoading();
    }
    app.getmatchdrawsheet(matchid, roundno, function (res) {
      console.log("getmatchdrawsheet-res");
      console.log(res);

      if (res.data.data.drawsheet) {
        that.setData({
          drawsheet: res.data.data.drawsheet
        })


      } else {
        that.setData({
          drawsheet: []
        })
      }
    }, function () {
      if (!autorefresh) {
        wx.hideNavigationBarLoading();
      }
    });









  },
  ///获取新闻类别
  getArtLists(count, offset) {

    var that = this;
    that.data.isloadingnews = true;

    app.getmedia("", that.data.matchinfo.matchid, "news", function (res) {
      console.log("getmedia-res");
      console.log(res);
      if (that.data.news_items && that.data.news_items.length > 0) {
        for (var index = 0; index < res.data.data.news.length; index++) {
          that.data.news_items.push(res.data[index]);
        }
      } else {
        that.setData({
          news_items: res.data.data.news
        })
      }
      that.setData({
        newspageoffset: that.data.newspageoffset + 1
      })
    }, offset?offset:that.data.newspageoffset, count, function () {
      wx.hideLoading();
    })

  },

  //打开playerscorecard 页面 
  _openplayerCard(e) {
    let playerorteam = e.detail.playerorteam; //是否是team团队成绩卡
    let selectid = e.detail.selectid;
    let matchinfo = e.detail.matchinfo;
    let playername = e.detail.playername;
    wx.navigateTo({
      url: '../Scorecard/player/index?selectid=' + selectid + "&playerorteam=" + playerorteam +
        "&playername=" + playername + "&matchinfo=" + encodeURIComponent(JSON.stringify(matchinfo)),
    })
    // 将参数的形式传递给父组件
  },

  
//打开playerscorecard 页面 
_openteamCard(e) {
  console.log(e);
  let selectid = e.detail.selectid;
  let matchinfo = JSON.parse(e.detail.matchinfo);
  let teamname = e.detail.teamname;
  wx.navigateTo({
    url: '../Scorecard/team/index?selectid=' + selectid +
      "&teamname=" + teamname + "&matchid=" + matchinfo.matchid,
  })
  // 将参数的形式传递给父组件
},

  //打开微信的新闻页面
  _opennews(e) {


    let news_itemobj = e.detail.newsitem;; //JSON.parse(newsitem.replace(" ", "").replace(/\ufeff/g, ""));

    if (news_itemobj.url != undefined) {
      this.setData({
        news_url: news_itemobj.url
      });

      wx.navigateTo({
        url: '../URL/index?weburl=' + encodeURIComponent(news_itemobj.url) + "&title=" + news_itemobj.title + "&type=新闻"
      })

    } else {

    }
  },

  ////提交报名方法
  _registerformSubmit(e) {


    var that = this;
    var data = e.detail.formdata;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.interfaeceregister,
      data: {
        data: data
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success(res) {

        wx.showToast({
      
          title: '提交成功',
        })
        if (that.data.islogin) {
          wx.setStorageSync('userinfo', res.data);
        }
        app.globalData.reguserinfo = res.data.data;
        wx.navigateTo({
          url: '../Register/index?playername=' + res.data.data.name + '&matchinfo=' + JSON.stringify(that.data.matchinfo)
        })

        console.log(res.data);
      },
      fail(res) {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      },
      complete() {
        wx.hideLoading()
      }
    })



  },

  ///切换菜单选项
  navTabChange(e) {
    var selected = e.currentTarget.dataset.currenttab;

    console.log(selected,'-----selected------2---------------');

    this.setData({
      currentTab: selected
    })
    this.setData({
      currentTab: e.currentTarget.dataset.currenttab
    });

    if(selected == 6){
       if(this.data.matchinfo.livesrc){
          wx.navigateTo({
            url: '../URL/index?weburl='+encodeURIComponent(this.data.matchinfo.livesrc)+'&title='+encodeURIComponent(this.data.matchinfo.matchname),
          })
       }
    }

    if (selected == 7) {
      if (this.data.islogin) {
        this.autosetregsterdata();
      }
    }
  },

  ///赛事detail
  swichNavmatchdetail(e) {
    var selected = e.currentTarget.dataset.current;

    this.setData({
      currentTabmatchinfo: selected
    })
  },

  //打开赛事信息页面
  _matchdetailopen(e) {
    let url = e.currentTarget.dataset.url; //JSON.parse(newsitem.replace(" ", "").replace(/\ufeff/g, ""));
    let type = e.currentTarget.dataset.type;
    let title = this.data.matchinfo.matchname;

    wx.navigateTo({
      url: '../URL/index?weburl=' + encodeURIComponent(url) + "&title=" + title + "&type='" + type
    })
  },

  login: function () {
    var that = this;
    app.wxlogin(app, function () {
      that.setData({
        islogin: true
      });
      that.autosetregsterdata();
    });
  },

  ///自动填充报名信息
  autosetregsterdata: function () {
    if (this.data.currentTab == 7) {
      if (wx.getStorageSync("autoreg") == '1') {
        var userinfo = wx.getStorageSync("userinfo");
        console.log(userinfo);
        if (userinfo != undefined) {
          var obj = this.selectComponent("#register");
          obj.filldata(userinfo.data);
        }
      }
    }

  },

  inputdata: function (e) {
    var register_info = this.data.register_info;
    var cat = e.target.id;
    var value = e.detail.value;
    console.log("inputdata");
    console.log(e);
    if (cat == "PlayerPoles") {
      register_info.PlayerPoles = value;
    }
    if (cat == "PlayerCoach") {
      register_info.PlayerCoach = value;
    }
    if (cat == "PlayerAcademy") {
      register_info.PlayerAcademy = value;
    }
    console.log(register_info);
    this.setData({
      register_info: register_info
    });
  },

  _errorshow: function (e) {
    var msg = e;
    console.log(msg);
    this.setData({
      error: ''
    });
    this.setData({
      error: msg
    })
  },

  getregisterinfo: function () {
    var that = this;
    wx.showLoading({
      title: '正在加载报名信息',
    })

    app.getregsiterinfo(that.data.matchinfo.matchid, function (res) {

        if (res.data.errorcode.code == "ok") {
          console.log("getregsiterinfo");
          console.log(res.data.data);
          if (res.data.data) {

            if (res.data.data.register && res.data.data.register.id) {

              //已经提交报名
             // that.changegroup(res.data.data, res.data.data.group, res.data.data.user_info.UserBirthday, res.data.data.register.id);

            } else {
             // that.changegroup(res.data.data, res.data.data.group, res.data.data.user_info.UserBirthday);
            }
            that.setData({
              playerinfo: res.data.data,
              PlayerSize:res.data.data.PlayerSize,
              submsg:res.data.data.submsg,
              isvistor: false,
              //PlayerHotelinfo: res.data.data.hotel,
            });
            that.setDefaultGroup();
            console.log('PlayerSize',that.data.PlayerSize);
           // var isoverage = that.checkisoverage(that.data.playerinfo.user_info.UserBirthday);
            //console.log(res.data.data);
           // that.setData({
           //   isoverage: !isoverage

          //  });

         //   that.geteventinfo();
          //  if (!isoverage) {
          //    that._errorshow("您的年龄不符合A/B/C组的年龄规定，请联系赛事管理员");
           //   that.setData({
          //      register_info: {}
           //   });
           // }
          } else {
            that.setData({
              playerinfo: {},
              isoverage: false,

            });
          }
        }
      },
      function (res) {
        console.log("getregsiterinfo-fail");
        console.log(res);

        wx.showToast({
          title: res.data.errorcode.message,
          icon: 'none',
          duration: 3000,
        })

      },
      function () {
        wx.hideLoading();
      })
 
  },

  geteventinfo: function () {
    var playerinfo = this.data.playerinfo;
    var events_id = playerinfo.events_id;
    var eventlists = "";
    var events_idarr = (events_id) ? events_id.split(',') : [];

    if (events_idarr.length > 0) {
      for (var index = 0; index < events_idarr.length; index++) {
        for (var eventindex = 0; eventindex < playerinfo.event.length; eventindex++) {
          console.log(playerinfo.event[eventindex]);
          if (playerinfo.event[eventindex].id == events_idarr[index]) {
            eventlists += playerinfo.event[eventindex].name + ','
            break;
          }
        }
      }
      console.log(eventlists);
      eventlists = eventlists.substring(0, eventlists.length - 1);
    }

    this.setData({
      eventlistsinfo: eventlists
    });
  },


  changedata1: function (e) {

    var register_info = this.data.register_info;
    var value = e.detail.value;
    var cat = e.target.id;
    console.log("changedata");
    console.log(e);
    if (cat == "PlayerBasicMatch") {
      register_info.PlayerBasicMatch = this.data.PlayerBasicMatch[value].mt_name;
    } else if (cat == "eventlist") {
      if (value == 0) {
        register_info.events_id = "";
      } else {
        var events_id = "";
        console.log(value.length);
        if (value && value.length > 0) {

          for (var index = 0; index < value.length; index++) {
            events_id += value[index] + ",";
            console.log(value[index]);
            console.log(events_id);
          }
          events_id = events_id.substring(0, events_id.length - 1);
        }
        register_info.events_id = events_id;
      }
    }
    this.setData({
      register_info: register_info
    });
    console.log(this.data.register_info);
  },

  changegroup: function (playerinfo, group, birthay, id) {
    console.log(group);
    for (var index = 0; index < group.length; index++) {

      if (group[index].name.indexOf("A") >= 0) {
        group[index].detail = "A组（U19）:13-18岁(生日:" + this.getage("A", group[index], birthay);
      }
      if (group[index].name.indexOf("B") >= 0) {
        group[index].detail = "B组（U13）:10-12岁(生日:" + this.getage("B", group[index], birthay);
      }
      if (group[index].name.indexOf("C") >= 0) {
        group[index].detail = "C组（U10）:6-9岁(生日:" + this.getage("C", group[index], birthay);
      }
     

      if (id && group[index].id == id) {
        group[index].ischecked = true;
      } else if (id && group[index].id == id) {
        group[index].ischecked = false;
      } else if (!id) {
        group[index].ischecked = (group[index].ischecked) ? group[index].ischecked : false;
      }
      console.log(group[index]);
      if (group[index].ischecked) {
        var register_info = this.data.register_info;
        var value = group[index].id;


        register_info.GroupID = value;
        this.setData({

          register_info: register_info,
          groupshouldbe: group[index],
        });
        console.log(this.data.isCgroup);
        console.log(this.data.groupshouldbe);
        this.changePlayerBasicMatch(playerinfo, group[index]);
      }
    }

    if (id) {

    }




    console.log(group);
  },

  changePlayerBasicMatch(playerinfo) {
    console.log("changePlayerBasicMatch");

    var matches = playerinfo.match;
    var PlayerBasicMatch = [];

    for (var groupcodetemp in matches) {
      console.log(groupcodetemp);
      for (var index in matches[groupcodetemp]) {
        matches[groupcodetemp][index].mt_name = matches[groupcodetemp][index].mt_name + '-' + groupcodetemp + '组';
        PlayerBasicMatch.push(matches[groupcodetemp][index]);
      }

    }

    this.setData({
      PlayerBasicMatch: PlayerBasicMatch
    });
    console.log(this.data.PlayerBasicMatch);
  },

  checkisoverage(birthay) {
    var matchinfo = this.data.matchinfo;
    var matchstartDate = matchinfo.matchstartDate;

    var agestart = "";
    var ageend = "";
    agestart = this.reduceyear(matchstartDate, 19, 0);
    ageend = this.reduceyear(matchstartDate, 6, -1);
    console.log(agestart);
    console.log(ageend);
    return this.checkage(agestart, ageend, birthay);

  },

  getage(groupcode, group, birthay) {
    var matchinfo = this.data.matchinfo;
    var matchstartDate = matchinfo.matchstartDate;
    var matchendDate = matchinfo.matchendDate;
    var agestart = "";
    var ageend = "";
    if (groupcode == 'A') {
      agestart = this.reduceyear(matchstartDate, 19, 0);
      ageend = this.reduceyear(matchstartDate, 13, -1);

    } else if (groupcode == 'B') {
      agestart = this.reduceyear(matchstartDate, 13, 0);
      ageend = this.reduceyear(matchstartDate, 10, -1);

    } else if (groupcode == 'C') {
      agestart = this.reduceyear(matchstartDate, 10, 0);
      ageend = this.reduceyear(matchstartDate, 6, -1);

    }else {

    }
    group.ischecked = this.checkage(agestart, ageend, birthay);

    return agestart + "-" + ageend + ")";
  },



  reduceyear(date, years, plus) {
    var date = new Date(date);
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    year = year - years;
    date = Date.parse(year + "/" + month + "/" + day);
    console.log(year + "/" + month + "/" + day);
    var timestamp;
    if (plus) {
      timestamp = date / 1000 + 24 * 60 * 60 * (plus);
    } else {
      timestamp = date / 1000;
    }

    timestamp = new Date(parseInt(timestamp) * 1000);
    console.log(timestamp);
    return timestamp.toLocaleDateString();
  },
  //检查年龄是否在这个组别
  checkage(agestart, ageend, birthay) {

    birthay = new Date(birthay);
    agestart = new Date(agestart);
    ageend = new Date(this.reduceyear(new Date(ageend), 0, 1));
    console.log(birthay);
    console.log(agestart);
    console.log(ageend);
    if (birthay >= agestart && birthay <= ageend) {
      console.log(agestart);
      return true;
    }
    return false;
  },

  changedata: function (e) {
    var register_info = this.data.register_info;
    var value = e.detail.value;
    var id = e.target.id;
    var playerinfo = this.data.playerinfo;
    var events = this.data.playerinfo.event;

    console.log(e);
    if (id == "PlayerIsCaddie") {
      register_info.PlayerIsCaddie = value;
    }
    if (id == "PlayerSize") {
      register_info.PlayerSize = this.data.PlayerSize[value];
    }
    if (id == "PlayerHotelRoom") {
      register_info.PlayerHotelRoom = value;
    }
    if (id == "PlayerIsHotel") {
      register_info.PlayerIsHotel = value;
    }
    if (id == "PlayerHotelStart") {
      register_info.PlayerHotelStart = value;
    }
    if (id == "PlayerHotelEnd") {
      register_info.PlayerHotelEnd = value;
    } else if (id == "eventlist") {
      var isnone = false;
      if (value.length > 1 && value[value.length - 1] == -1) {
        isnone = true;
      }
      if (isnone) {
        register_info.events_id = "";
        //this.setData({ischecknone:true,})
        for (var index = 0; index < events.length; index++) {

          events[index].checked = false;
          console.log(events[index]);
          console.log(events);

        }
        //playerinfo.event = events;
        //this.setData({playerinfo:playerinfo,})
      } else {
        // this.setData({ischecknone:false,})
        var events_id = "";
        console.log(value.length);
        if (value && value.length > 0) {
          // var deletindex = -1;
          for (var eventindex = 0; eventindex < events.length; eventindex++) {
            var index = 0;
            for (; index < value.length; index++) {
              if (value[index] == -1) {
                continue;
              }
              if (eventindex == value[index]) {
                events[value[index]].checked = true;
                events_id += events[value[index]].id + ",";
                break;
              }


              //events[value[index]].checked = true;
              console.log(value[index]);
              console.log(events);

            }

            if (index == value.length) {
              events[eventindex].checked = false;
            }

          }
          //playerinfo.event = events;
          events_id = events_id.substring(0, events_id.length - 1);
          //this.setData({playerinfo:playerinfo,})
        }
        register_info.events_id = events_id;
      }
    }

    this.setData({
      register_info: register_info
    })

    console.log(this.data.register_info);
  },

  setDefaultGroup: function () {
    console.log("setDefaultGroup-------------------------",);
    const { playerinfo, register_info } = this.data;

    console.log("setDefaultGroup----------playerinfo---------------",playerinfo);

    console.log("setDefaultGroup---------register_info----------------",register_info);
    if (playerinfo.group && playerinfo.group.length > 0) {
      const gender = register_info.Gender || '男';
      const defaultGroup = playerinfo.group.find(group => 
        gender === '男' ? group.name.includes('男') : group.name.includes('女')
      );
      
      if (defaultGroup) {
        register_info.GroupID = defaultGroup.id;
        this.setData({ register_info });
      }
    }
  },

  setDefaultGroup: function () {
    console.log("setDefaultGroup-------------------------",);
    const { playerinfo, register_info } = this.data;

    console.log("setDefaultGroup----------playerinfo---------------",playerinfo);

    console.log("setDefaultGroup---------register_info----------------",register_info);
    if (playerinfo.group && playerinfo.group.length > 0) {
      const gender = register_info.Gender || '男';
      const defaultGroup = playerinfo.group.find(group => 
        gender === '男' ? group.name.includes('男') : group.name.includes('女')
      );
      
      if (defaultGroup) {
        register_info.GroupID = defaultGroup.id;
        this.setData({ register_info });
      }
    }
  },

  changegroupradioes:function(e) {
      var id = e.detail.value;
      let{ register_info} = this.data;
      register_info.GroupID = id;
      this.setData({register_info});
  }
  ,
  commit: function () {
    var register_info = this.data.register_info;

    var isoverage = this.data.isoverage;
    if (isoverage) {
      this._errorshow("您的年龄不符合A/B/C的年龄规定，请联系赛事管理员");
      return;
    }


    if (!register_info.PlayerPoles) {
      this._errorshow("请输入杆数");
      return;
    } else if (!register_info.PlayerSize) {
      this._errorshow("请选择衣服尺码");
      return;
    } else if (this.data.playerinfo.hotel.isrequired && (!(register_info.PlayerIsHotel == "0" || register_info.PlayerIsHotel == "1"))) {
      this._errorshow("请选择是否入住官方酒店");
      return;
    } else if (register_info.PlayerIsHotel == 1 && (!(register_info.PlayerHotelRoom == "0" || register_info.PlayerHotelRoom == "1"))) {
      this._errorshow("请选择入住房型");
      return;
    } else if (register_info.PlayerIsHotel == 1 && !register_info.PlayerHotelStart) {
      this._errorshow("请选择入住日期");
      return;
    } else if (register_info.PlayerIsHotel == 1 && !register_info.PlayerHotelEnd) {
      this._errorshow("请选择离开日期");
      return;
    } /*else if ((this.data.playerinfo.PlayerIsCaddie) && !(register_info.PlayerIsCaddie == "0" || register_info.PlayerIsCaddie == "1")) {
      this._errorshow("请选择是否自带球童");
      return;
    } else if ((this.data.playerinfo.PlayerIsCoach) && (register_info.PlayerCoach == "")) {
      this._errorshow("请填写教练");
      return;
    } else if ((this.data.playerinfo.PlayerIsCoach) && (register_info.PlayerAcademy == "")) {
      this._errorshow("请填写高尔夫学院");
      return;
    }*/

    var that = this;
    this.setData({
      iscommitregister: true
    })
    wx.showLoading({
      title: "正在提交报名申请"
    });
    app.commitregsiterinfo(this.data.matchinfo.matchid, register_info, function (res) {
      if (res.data.errorcode.code == "ok") {

        that.setData({
          iscommitregister: false
        })
        var register_id = res.data.data;
        if (register_id) {
          
          that.getfiledlist(false);
          wx.requestSubscribeMessage({
            tmplIds: that.data.submsg,
            success (res) { },
            fail(res){console.log(res)}
          });
            //支付成功跳转
            //跳转到成功页面
            var succuss = {
              message: that.data.playerinfo.user_info.UserTrueName + "\n" + that.data.matchinfo.matchname + "\n 报名提交成功",
              time: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
              back: true,
              buttoninfo: "返回"
            }
            // wx.hideLoading();

            wx.navigateTo({
              url: '/pages/succuss/index?succuss=' + JSON.stringify(succuss)
            })
          // that.wxpay(register_id);
        }
      } else {
        wx.showToast({
          title: res.data.errorcode.message,
          icon: 'error',
          duration: 5000
        })
      }
    }, function () {
      wx.hideLoading();
      that.setData({
        iscommitregister: false
      })
    });

  },

  wxrepay:function(e){
    var register_id = e.currentTarget.dataset.registerid;
    if(register_id){
      this.wxpay(register_id);
    }
  },

  wxpay: function (register_id) {
    var that = this;
    app.wxpay(register_id,
      function (res) {
        console.log(res);
        wx.requestPayment({
          timeStamp: res.data.data.timeStamp,
          nonceStr: res.data.data.nonceStr,
          package: res.data.data.package,
          signType: res.data.data.signType,
          paySign: res.data.data.paySign,
          success: function (resdata) {
            /*wx.showModal({
              title: '支付成功',
              content: '',
              showCancel: false,
            })*/

            that.getfiledlist(false);

            //支付成功跳转
            //跳转到成功页面
            var succuss = {
              message: that.data.playerinfo.user_info.UserTrueName + "\n" + that.data.matchinfo.matchname + "\n 报名支付成功",
              time: new Date().toLocaleDateString() + " " + new Date().toLocaleTimeString(),
              back: true,
              buttoninfo: "返回"
            }
            // wx.hideLoading();

            wx.navigateTo({
              url: '/pages/succuss/index?succuss=' + JSON.stringify(succuss)
            })
          },
          fail: function (resdata) {
            console.log(resdata);
            wx.showModal({
              title: '支付失败',
              content: '请尽快到个人中心中报名列表未支付的赛事中支付赛事报名费',
              showCancel: false,
            })

            that.getregisterinfo(false);
          }
        })


      },
      function () {});
  },


  changecardno: function () {
    wx.navigateTo({
      url: '/pages/More/information/information?ismodify=1',
    })
  },

  gotocenter: function () {
    wx.navigateTo({
      url: '/pages/More/information/information?match_id='+(this.data.matchid?this.data.matchid:this.data.matchinfo.matchid),
    })
  },

  changebanduserlists: function (e) {

    var currentuserInfo = this.data.currentuserInfo;
    var banduserlists = currentuserInfo.banduserlists;
    var value = e.detail.value;

    console.log("changebanduserlistsfunction");
    console.log(e);

    app.globalData.userInfo.trueName = banduserlists[value].truename;
    app.globalData.userInfo.openid = banduserlists[value].openid;
    app.globalData.userInfo.userID = banduserlists[value].userid;
    app.globalData.userInfo.player_id = banduserlists[value].player_id;
    app.globalData.userInfo.cardnumber = banduserlists[value].cardnumber;
    console.log(app.globalData.userInfo);
    this.setData({
      currentuserInfo: app.globalData.userInfo
    });
    this.getregisterinfo();

  },
  openQrcode() {
    if (!(this.data.mytour && this.data.mytour.playerscores)) return
    var that = this;
    var userInfo =  app.globalData.userInfo?app.globalData.userInfo: wx.getStorageSync('userInfo');
  var that = this;
    // this.setData({playerinfo:userInfo});
    app.getplayerscorecard(this.data.matchid?this.data.matchid:this.data.matchinfo.matchid,
      userInfo.player_id,
      function(res){
       // console.log(res.data.data);
        that.setData({playerScoresDisplay:res.data.data});
        that.selectComponent("#canvas-popup").showPopup(res.data.data,userInfo);
    },
    function(){

    }
    );
},

  opendealer: function (e) {
    const ml_id = e.currentTarget.dataset.ml_id;

  wx.navigateTo({
    url: `/pages/Dealer/index?ml_id=${ml_id}`
  });
},

  previewAwardsImg: function(e) {
    const currentImg = e.currentTarget.dataset.img;
    wx.previewImage({
      current: currentImg, // 当前显示图片的链接
      urls: [currentImg] // 需要预览的图片链接列表
    })
  }
})